package com.itheima.springmybatis.aop;

import com.alibaba.fastjson.JSON;
import com.itheima.springmybatis.dao.UserMapper;
import com.itheima.springmybatis.domain.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

@Aspect
@Component
public class UserLog {
    @Autowired
    private UserMapper userMapper;

    @Pointcut("execution(* com.itheima.springmybatis.controller.UserController.*(..))")
    public void pointcut(){
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        Object obj = null;
        try {
            long start = System.currentTimeMillis();
            obj = joinPoint.proceed();
            long end = System.currentTimeMillis();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = dateFormat.format(start);

            Log log = new Log();
            log.setAccessTime(format);
            log.setConsumedTime(end - start);
            log.setMethodName(joinPoint.getSignature().getName());
            log.setPathName(joinPoint.getSignature().getDeclaringTypeName());
            String logString = JSON.toJSONString(log);
            userMapper.setUserLog(log);

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }
}
